package com.xzt.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzt.bookstore.dto.*;
import com.xzt.bookstore.entity.*;
import com.xzt.bookstore.mapper.OrderItemMapper;
import com.xzt.bookstore.mapper.OrderMapper;
import com.xzt.bookstore.service.BookService;
import com.xzt.bookstore.service.CartService;
import com.xzt.bookstore.service.OrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单服务实现类
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    
    private final OrderItemMapper orderItemMapper;
    private final CartService cartService;
    private final BookService bookService;
    
    public OrderServiceImpl(OrderItemMapper orderItemMapper, CartService cartService, BookService bookService) {
        this.orderItemMapper = orderItemMapper;
        this.cartService = cartService;
        this.bookService = bookService;
    }
    
    @Override
    @Transactional
    public OrderDTO createOrderFromCart(Long userId, OrderCreateRequest request) {
        // 获取购物车列表
        List<CartItemDTO> cartItems = cartService.getCartList(userId);
        
        // 如果指定了购物车ID列表，则只选择指定的商品
        if (request.getCartIds() != null && !request.getCartIds().isEmpty()) {
            cartItems = cartItems.stream()
                    .filter(item -> request.getCartIds().contains(item.getCartId()))
                    .collect(Collectors.toList());
        }
        
        if (cartItems.isEmpty()) {
            throw new RuntimeException("购物车为空，无法创建订单");
        }
        
        // 验证库存
        for (CartItemDTO item : cartItems) {
            Book book = bookService.getById(item.getBookId());
            if (book == null) {
                throw new RuntimeException("图书不存在：" + item.getBookName());
            }
            if (book.getStatus() == 0) {
                throw new RuntimeException("图书已下架：" + item.getBookName());
            }
            if (book.getStock() < item.getQuantity()) {
                throw new RuntimeException("库存不足：" + item.getBookName() + "，当前库存：" + book.getStock());
            }
        }
        
        // 计算总金额
        BigDecimal totalAmount = cartItems.stream()
                .map(item -> item.getSubtotal())
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        // 生成订单号（时间戳 + 用户ID）
        String orderNo = generateOrderNo(userId);
        
        // 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setOrderNo(orderNo);
        order.setTotalAmount(totalAmount);
        order.setStatus(0); // 待支付
        this.save(order);
        
        // 创建订单项
        for (CartItemDTO cartItem : cartItems) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setBookId(cartItem.getBookId());
            orderItem.setBookName(cartItem.getBookName());
            orderItem.setAuthor(cartItem.getAuthor());
            orderItem.setPrice(cartItem.getPrice());
            orderItem.setQuantity(cartItem.getQuantity());
            orderItem.setSubtotal(cartItem.getSubtotal());
            orderItemMapper.insert(orderItem);
        }
        
        // 从购物车删除已下单的商品
        for (CartItemDTO cartItem : cartItems) {
            cartService.removeFromCart(userId, cartItem.getCartId());
        }
        
        // 返回订单DTO
        return convertToDTO(order);
    }
    
    @Override
    public List<OrderDTO> getUserOrders(Long userId) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, userId)
               .orderByDesc(Order::getCreateTime);
        List<Order> orders = this.list(wrapper);
        
        return orders.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    @Override
    public OrderDTO getOrderById(Long userId, Long orderId) {
        Order order = this.getById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            throw new RuntimeException("无权访问该订单");
        }
        return convertToDTO(order);
    }
    
    @Override
    @Transactional
    public void cancelOrder(Long userId, Long orderId) {
        Order order = this.getById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            throw new RuntimeException("无权操作该订单");
        }
        if (order.getStatus() != 0) {
            throw new RuntimeException("只能取消待支付的订单");
        }
        
        order.setStatus(2); // 已取消
        this.updateById(order);
    }
    
    /**
     * 生成订单号
     */
    private String generateOrderNo(Long userId) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        return "ORD" + timestamp + String.format("%06d", userId);
    }
    
    /**
     * 转换为DTO
     */
    private OrderDTO convertToDTO(Order order) {
        OrderDTO dto = new OrderDTO();
        dto.setId(order.getId());
        dto.setUserId(order.getUserId());
        dto.setOrderNo(order.getOrderNo());
        dto.setTotalAmount(order.getTotalAmount());
        dto.setStatus(order.getStatus());
        dto.setStatusDesc(getStatusDesc(order.getStatus()));
        dto.setCreateTime(order.getCreateTime());
        dto.setUpdateTime(order.getUpdateTime());
        
        // 查询订单项
        LambdaQueryWrapper<OrderItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderItem::getOrderId, order.getId());
        List<OrderItem> orderItems = orderItemMapper.selectList(wrapper);
        
        List<OrderItemDTO> itemDTOs = orderItems.stream().map(item -> {
            OrderItemDTO itemDTO = new OrderItemDTO();
            itemDTO.setId(item.getId());
            itemDTO.setBookId(item.getBookId());
            itemDTO.setBookName(item.getBookName());
            itemDTO.setAuthor(item.getAuthor());
            itemDTO.setPrice(item.getPrice());
            itemDTO.setQuantity(item.getQuantity());
            itemDTO.setSubtotal(item.getSubtotal());
            return itemDTO;
        }).collect(Collectors.toList());
        
        dto.setItems(itemDTOs);
        return dto;
    }
    
    /**
     * 获取状态描述
     */
    private String getStatusDesc(Integer status) {
        switch (status) {
            case 0:
                return "待支付";
            case 1:
                return "已支付";
            case 2:
                return "已取消";
            default:
                return "未知";
        }
    }
}

